package com.example.chat03.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

/**
 * Websocket 连接外部消息代理配置
 */
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketExternalMessageBrokerConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        // 拦截器配置
        registration.interceptors(new UserAuthenticationChannelInterceptor());
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/websocket")// WebSocket握手端点
                .setAllowedOriginPatterns("*")// 设置跨域
                .withSockJS()
        ;
    }

//    @Override
//    public void configureMessageBroker(MessageBrokerRegistry registry) {
//        registry.setApplicationDestinationPrefixes("/app")// 发送到服务端目的地前缀
//                .enableSimpleBroker("/topic")// 开启外部消息代理，指定消息订阅前缀
//        ;
//    }

    /**
     * 外部消息代理(rabbitmq)配置
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.setApplicationDestinationPrefixes("/app")// 发送到服务端目的地前缀
                .enableStompBrokerRelay("/topic","/queue")// 开启外部消息代理，指定消息订阅前缀
                .setRelayHost("192.168.11.140")// 外部消息代理 Host
                .setRelayPort(61613)// 外部消息代理STOMP端口
                .setSystemLogin("guest")// 共享系统连接用户名，该连接主要用来发送消息
                .setSystemPasscode("guest")// 共享系统连接密码，该连接主要用来发送消息
                .setClientLogin("guest")// 客户端连接用户名，该连接主要用来接收消息
                .setClientPasscode("guest")// 客户端连接密码，该连接主要用来接收消息
                .setVirtualHost("/stomp")// RabbitMQ虚拟主机
        ;
    }
}
